import requests
import os
from notify import send
##cron: 0 12 30 * *
##new Env("华燃燃气")
def get_user_info(app_id, open_id, user_code):
    url = "https://tyyvzt.vs-gascloud.com/customer/getUserInfo"
    headers = {
        "Host": "tyyvzt.vs-gascloud.com",
        "charset": "utf-8",
        "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/138.0.7204.180 Mobile Safari/537.36 XWEB/1380283 MMWEBSDK/20221011 MMWEBID/9222 MicroMessenger/8.0.30.2260(0x28001E3B) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android",
        "content-type": "application/json",
        "Accept-Encoding": "gzip,compress,br,deflate",
        "Referer": "https://servicewechat.com/wxcd101a261ae223df/3/page-frame.html"
    }
    
    # 使用传入的参数构建数据
    data = {
        "regChannel": "WECHAT",
        "channel": "WECHAT",
        "appId": app_id,
        "openId": open_id,
        "companyCode": "1402",
        "userCode": user_code,
        "custCode": user_code,
    }

    res = requests.post(url, headers=headers, json=data)
    return res.json()

def hide_meter_number(meter_no):
    """隐藏燃气表号中间数字"""
    if len(meter_no) > 4:
        return meter_no[:4] + "*" * (len(meter_no) - 8) + meter_no[-4:]
    return meter_no

def parse_env_variable(env_var):
    """解析环境变量，格式为 appId#openId#userCode"""
    if not env_var:
        return None, None, None
    
    parts = env_var.split('#')
    if len(parts) != 3:
        return None, None, None
    
    return parts[0], parts[1], parts[2]

# 主程序
if __name__ == "__main__":
    # 从青龙环境变量获取参数
    hrrq_env = os.environ.get('hrrq')
    
    if not hrrq_env:
        error_msg = "❌ 环境变量 hrrq 未设置，请检查配置"
        send("💥 燃气查询错误", error_msg)
        print(error_msg)
        exit(1)
    
    # 解析环境变量
    app_id, open_id, user_code = parse_env_variable(hrrq_env)
    
    if not all([app_id, open_id, user_code]):
        error_msg = f"❌ 环境变量 hrrq 格式错误，应为: appId#openId#userCode\n当前值: {hrrq_env}"
        send("💥 燃气查询错误", error_msg)
        print(error_msg)
        exit(1)
    
    try:
        print(f"🔧 开始查询燃气信息...")
        print(f"   AppID: {app_id}")
        print(f"   OpenID: {open_id}")
        print(f"   用户码: {user_code}")
        
        result = get_user_info(app_id, open_id, user_code)
        
        # 构建通知内容
        notification_title = "🔥 燃气查询 🔥"
        notification_content = ""
        
        if result.get('resultCode') == "0":
            notification_content += "✅ 查询状态: 成功\n\n"
            notification_content += f"👤 用户状态: {result.get('userStatus', '未知')}\n"
            
            # 处理燃气表信息
            if result.get('meterList'):
                meter = result['meterList'][0]
                hidden_meter_no = hide_meter_number(meter.get('meterNo', ''))
                
                notification_content += f"\n📊 燃气表信息:\n"
                notification_content += f"   🔢 表号: {hidden_meter_no}\n"
                notification_content += f"   ⛽ 剩余气量: {meter.get('remainVolumn', '0')} 立方米\n"
                notification_content += f"   💰 剩余金额: {meter.get('remainMoney', '0')} 元\n"
                notification_content += f"   📈 当前气价: {meter.get('meterPrice', '0')} 元/立方米\n"
                notification_content += f"   📊 累计用气: {meter.get('accumulatedVolumn', '0')} 立方米\n"
                
                # 添加温馨提示
                remain_volumn = float(meter.get('remainVolumn', 0))
                if remain_volumn < 10:
                    notification_content += f"\n⚠️ 温馨提示: 剩余气量不足，请及时充值！\n"
                elif remain_volumn < 30:
                    notification_content += f"\n💡 温馨提示: 剩余气量较少，建议提前充值\n"
                else:
                    notification_content += f"\n💚 温馨提示: 气量充足，无需担心\n"
                
                # 发送通知
                send(notification_title, notification_content)
                print("🎉 通知发送成功！")
            else:
                notification_content = "❌ 未找到燃气表信息"
                send(notification_title, notification_content)
        else:
            error_msg = result.get('resultMsg', '未知错误')
            notification_content = f"❌ 查询失败: {error_msg}"
            send(notification_title, notification_content)
            print(f"❌ 查询失败: {error_msg}")
            
    except Exception as e:
        error_msg = f"❌ 查询过程中出现错误: {str(e)}"
        send("💥 燃气查询错误", error_msg)
        print(error_msg)